﻿Imports System.IO
Imports System.Deployment.Application
Imports Microsoft.SqlServer.Server
Imports System.Net

Public Class frm_display
    Public ShopName As String
    Public MyDate As String
    Public LstRecord As List(Of Record) = New List(Of Record)()
    Public TimeSche As TimeSchedule = New TimeSchedule()
    Public Plan As Integer = 0
    Public Actual As Integer = 0
    Public Diff As Integer = 0
    Public Status As String = ""
    Public DuringTime As Integer = 0

    Public LstItem As List(Of Item) = New List(Of Item)()
    'to save list of item at begining of day => count plan
    Public LstTargetToday As List(Of Item) = New List(Of Item)()
    Public IsNewDate As Boolean = True

    Public WithEvents Tcp As TCPChat = New TCPChat()
    Public HostAddr As String
    Public HostPort As Integer
    Public RemoteAddr As String
    Public RemotePort As Integer

    'count how many sending msg to host (for 1 msg)
    Public CountTimesSendingMsg As Integer = 0


    Private Sub frm_display_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        GetConfigFile()

        'create list item
        AddPendingToLstItem()

        'if IsNewDate, at begining day
        If IsNewDate Then
            GetSchedule()
            AddScheduleToLstItem()
            SaveTargetToday()
            AddTargetToLstTarget()
            ResetStatusAndNumber()
            'if power-off
        Else
            AddTargetToLstTarget()
            'Status = GetStatus()
        End If

        GetTimerFile()
        GetNumberFile()
        Status = GetStatusNow()

        'Plan = CountPlan()

        SetInitLabel()
        Timer1.Enabled = True
        Timer1.Interval = 60000

        TimerSendMsg.Interval = 3000

        'lblStatus.Text = CountWorkingTimeToNow().ToString()

        ConnetTCP()
        '-------------------------------------

        'Dim da As DateTime = DateTime.Now
        'Dim asd As String = ConvertTimeToString(da)

        'lblStatus.Text = da.ToString("MM/dd/yyyy").Replace("/", "")
        'lblStatus.Text = da.ToString("HH:mm")

        'Dim time As Integer = 0
        'Dim starTime As DateTime = DateTime.ParseExact("07:30", "HH:mm", Nothing)
        'Dim endTime As DateTime = DateTime.ParseExact("06:00", "HH:mm", Nothing)
        'Dim timeSpan As TimeSpan = endTime - starTime
        'time = CInt(timeSpan.TotalMinutes)
        'lblStatus.Text = time


        Dim test As String
        'Dim a As String = "21:00"
        'Dim b As String = "10:30"
        'lblStatus.Text = a.CompareTo(b).ToString()

        'lblStatus.Text = CountWorkingTimeToNow()

        'test = "SCHE|11232014|ABC|2|3|5|ZXC|4|2|1"
        'SaveScheMsg(test)
        'test = "ASKS|11202014"
        'ReplyAskSchedule(test)

    End Sub

    Public Sub GetConfigFile()
        Try
            Using sr As New StreamReader("ClientSetting.ini")
                Dim line As String

                line = sr.ReadLine()
                ShopName = line

                line = sr.ReadLine()
                RemoteAddr = line

                line = sr.ReadLine()
                RemotePort = Integer.Parse(line)
            End Using
        Catch e As Exception
            MessageBox.Show("'ClientSetting.ini' could not be read!")
        End Try
    End Sub

    Public Sub GetNumberFile()
        Try
            Using sr As New StreamReader("number.txt")
                Dim dateInFile As String = sr.ReadLine()
                Dim today As String = DateTime.Now.ToString("MM/dd/yyyy")

                If today.Equals(dateInFile) Then
                    Dim line As String

                    'do nothing with plan no in file. plan no must be counted again
                    line = sr.ReadLine()
                    Plan = CountPlan()

                    line = sr.ReadLine()
                    Actual = Integer.Parse(line)

                    line = sr.ReadLine()
                    Diff = Integer.Parse(line)
                Else
                    Plan = 0
                    Actual = 0
                    Diff = 0
                End If
            End Using
        Catch e As Exception
            MessageBox.Show("'number.txt' could not be read!")
        End Try
    End Sub

    Public Sub SaveNumberFile()
        Try
            Dim file As New StreamWriter("number.txt")
            file.WriteLine(DateTime.Now.ToString("MM/dd/yyyy"))
            file.WriteLine(Plan.ToString())
            file.WriteLine(Actual.ToString())
            file.WriteLine(Diff.ToString())
            file.Close()
        Catch e As Exception
            MessageBox.Show("Cannot save to 'number.txt'!")
        End Try
    End Sub

    Public Sub ResetStatusAndNumber()
        Status = ""
        SaveStatus(Status)
        Plan = 0
        Actual = 0
        Diff = 0
        SaveNumberFile()
    End Sub

    Public Sub GetSchedule()
        Dim strToday As String = DateTime.Now.ToString("MM/dd/yyyy").Replace("/", "")
        Dim path As String = "schedule_" + strToday + ".txt"
        Try
            Using sr As New StreamReader(path)
                MyDate = sr.ReadLine()
                Dim line As String
                While sr.Peek() <> -1
                    line = sr.ReadLine()
                    'Dim split As String() = line.Split(New [Char]() {"|"c, CChar(vbTab) })
                    Dim split As String() = line.Split("|")
                    Dim record As Record = New Record()
                    record.Model = split(0)
                    record.Volumn = split(1)
                    record.TimeToChange = split(2)
                    record.Duration = split(3)
                    LstRecord.Add(record)
                End While
            End Using
        Catch e As Exception
            MessageBox.Show("The schedule file could not be read!")
        End Try
    End Sub

    Public Function CountTarget() As Integer
        Dim totalUnit As Integer = 0
        For Each record As Record In LstRecord
            totalUnit += record.Volumn
        Next
        Return totalUnit
    End Function

    Public Sub AddScheduleToLstItem()
        'compare last model in pending list and first model in schedule
        'if different, add 1 item has duration = time to change of last item in pending list
        If LstItem.Count > 0 Then
            Dim lastModel As String = LstItem(LstItem.Count - 1).Model
            If (Not lastModel.Equals(LstRecord(0).Model)) AndAlso (Not lastModel.Equals("change")) Then
                LstItem.Add(New Item("change", LstItem(LstItem.Count - 1).TimeToChange, LstItem(LstItem.Count - 1).TimeToChange))
            End If
        End If

        For Each record As Record In LstRecord
            For i As Integer = 0 To record.Volumn - 1
                LstItem.Add(New Item(record.Model, record.Duration, record.TimeToChange))
            Next
            LstItem.Add(New Item("change", record.TimeToChange, record.TimeToChange))
        Next
        LstItem.RemoveAt(LstItem.Count - 1)
    End Sub

    Public Sub SetLblTarget()
        'Dim totalUnit As Integer = CountTarget()

        Dim noOfChange = LstItem.FindAll(Function(p) p.Model.Equals("change")).Count
        Dim totalUnit As Integer = LstItem.Count - noOfChange
        Dim s As String
        s = "Today Target: " + totalUnit.ToString() + " units"
        lblTarget.Text = s
    End Sub

    Public Sub SetInitLabel()
        Dim now As DateTime = DateTime.Now
        lblTime.Text = now.ToString("HH:mm")
        lblShop.Text = ShopName
        lblStatus.Text = Status
        lblDate.Text = DateTime.Now.ToString("MM/dd/yyyy")
        SetLblTarget()
        lblPlan.Text = Plan.ToString()
        lblActual.Text = Actual.ToString()
        lblDiff.Text = Diff.ToString()
    End Sub

    Public Sub GetTimerFile()
        Try
            Using sr As New StreamReader("timer.txt")
                Dim line As String

                line = sr.ReadLine()
                TimeSche.MorStart = line
                line = sr.ReadLine()
                TimeSche.MorBreakStart = line
                line = sr.ReadLine()
                TimeSche.MorBreakEnd = line
                line = sr.ReadLine()
                TimeSche.LunchStart = line
                line = sr.ReadLine()
                TimeSche.LunchEnd = line
                line = sr.ReadLine()
                TimeSche.NoonStart = line
                line = sr.ReadLine()
                TimeSche.NoonBreakStart = line
                line = sr.ReadLine()
                TimeSche.NoonBreakEnd = line
                line = sr.ReadLine()
                TimeSche.NoonEnd = line

                If sr.Peek() <> -1 Then
                    line = sr.ReadLine()
                    TimeSche.OTStart = line
                    line = sr.ReadLine()
                    TimeSche.OTEnd = line
                End If
            End Using
        Catch e As Exception
            MessageBox.Show("Invalid file timer.txt!")
        End Try
    End Sub

    Public Function ConvertTimeToString(ByVal time As DateTime) As String
        Dim s As String
        Dim hour As String
        Dim min As String

        hour = time.Hour.ToString()
        If hour.Length = 1 Then
            hour = "0" + hour
        End If

        min = time.Minute.ToString()
        If min.Length = 1 Then
            min = "0" + min
        End If

        s = hour + ":" + min
        Return s
    End Function

    Public Function GetStatus() As String
        Dim line As String = ""
        Try
            Using sr As New StreamReader("status.txt")
                While sr.Peek() <> -1
                    line = sr.ReadLine()
                End While
            End Using
        Catch e As Exception
            MessageBox.Show("Cannot get status!")
        End Try
        Return line
    End Function

    Public Sub SaveStatus(ByVal stt As String)
        Try
            Dim file As New StreamWriter("status.txt")
            file.WriteLine(stt)
            file.Close()
        Catch e As Exception
            MessageBox.Show("'status.txt' could not be read!")
        End Try
    End Sub

    Public Sub AddPendingToLstItem()
        Try
            Using sr As New StreamReader("pending.txt")
                Dim dateInFile As String = sr.ReadLine()
                Dim today As String = DateTime.Now.ToString("MM/dd/yyyy")
                If today.Equals(dateInFile) Then
                    IsNewDate = False
                Else
                    IsNewDate = True
                End If

                Dim line As String
                While sr.Peek() <> -1
                    line = sr.ReadLine()
                    Dim split As String() = line.Split("|")
                    Dim mo As String = split(0)
                    Dim du As String = split(1)
                    Dim ttc As String = split(2)
                    Dim iDu As Integer = Integer.Parse(du)
                    Dim iTtc As Integer = Integer.Parse(ttc)
                    Dim item As Item = New Item(mo, iDu, iTtc)
                    'LstItem.Insert(0, item)
                    LstItem.Add(item)
                End While
            End Using
        Catch e As Exception
            MessageBox.Show("'pending.txt' could not be read!")
        End Try
    End Sub

    Public Sub SavePendingFile()
        Try
            Dim file As New StreamWriter("pending.txt")
            file.WriteLine(DateTime.Now.ToString("MM/dd/yyyy"))

            For Each item As Item In LstItem
                file.WriteLine(item.Model + "|" + item.Duration.ToString() + "|" + item.TimeToChange.ToString())
            Next

            'For i As Integer = LstItem.Count - 1 To 0
            '    file.WriteLine(LstItem(i).Model + "|" + LstItem(i).Duration.ToString())
            'Next

            file.Close()
        Catch e As Exception
            MessageBox.Show("'pending.txt' could not be editted!")
        End Try
    End Sub

    Public Function CountTimeSpan(ByVal startT As String, ByVal endT As String) As Integer
        Dim time As Integer = 0
        Dim starTime As DateTime = DateTime.ParseExact(startT, "HH:mm", Nothing)
        Dim endTime As DateTime = DateTime.ParseExact(endT, "HH:mm", Nothing)
        Dim timeSpan As TimeSpan = endTime - starTime
        time = CInt(timeSpan.TotalMinutes)
        Return time
    End Function

    Public Function CountWorkingTimeToNow() As Integer
        Dim workingTime As Integer = 0
        Dim now As String = DateTime.Now.ToString("HH:mm")

        'If now.CompareTo(TimeSche.MorStart) < 0 Then
        '    workingTime = CountTimeSpan(now, TimeSche.MorStart)
        'Else
        If now.CompareTo(TimeSche.MorBreakStart) < 0 Then
            workingTime = CountTimeSpan(TimeSche.MorStart, now)
        Else
            If now.CompareTo(TimeSche.MorBreakEnd) < 0 Then
                workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart)
            Else
                If now.CompareTo(TimeSche.LunchStart) < 0 Then
                    workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                        + CountTimeSpan(TimeSche.MorBreakEnd, now)
                Else
                    If now.CompareTo(TimeSche.NoonStart) < 0 Then
                        workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                            + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart)
                    Else
                        If now.CompareTo(TimeSche.NoonBreakStart) < 0 Then
                            workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                + CountTimeSpan(TimeSche.NoonStart, now)
                        Else
                            If now.CompareTo(TimeSche.NoonBreakEnd) < 0 Then
                                workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                    + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                    + CountTimeSpan(TimeSche.NoonStart, TimeSche.NoonBreakStart)
                            Else
                                If now.CompareTo(TimeSche.NoonEnd) < 0 Then
                                    workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                        + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                        + CountTimeSpan(TimeSche.NoonStart, TimeSche.NoonBreakStart) _
                                        + CountTimeSpan(TimeSche.NoonBreakEnd, now)
                                Else
                                    'if not OT
                                    If TimeSche.OTStart.Length = 0 Then
                                        workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                            + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                            + CountTimeSpan(TimeSche.NoonStart, TimeSche.NoonBreakStart) _
                                            + CountTimeSpan(TimeSche.NoonBreakEnd, TimeSche.NoonEnd)
                                    Else
                                        'if OT
                                        If now.CompareTo(TimeSche.OTStart) < 0 Then
                                            workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                                + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                                + CountTimeSpan(TimeSche.NoonStart, TimeSche.NoonBreakStart) _
                                                + CountTimeSpan(TimeSche.NoonBreakEnd, TimeSche.NoonEnd)
                                        Else
                                            If now.CompareTo(TimeSche.OTEnd) < 0 Then
                                                workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                                    + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                                    + CountTimeSpan(TimeSche.NoonStart, TimeSche.NoonBreakStart) _
                                                    + CountTimeSpan(TimeSche.NoonBreakEnd, TimeSche.NoonEnd) _
                                                    + CountTimeSpan(TimeSche.OTStart, now)
                                            Else
                                                workingTime = CountTimeSpan(TimeSche.MorStart, TimeSche.MorBreakStart) _
                                                    + CountTimeSpan(TimeSche.MorBreakEnd, TimeSche.LunchStart) _
                                                    + CountTimeSpan(TimeSche.NoonStart, TimeSche.NoonBreakStart) _
                                                    + CountTimeSpan(TimeSche.NoonBreakEnd, TimeSche.NoonEnd) _
                                                    + CountTimeSpan(TimeSche.OTStart, TimeSche.OTEnd)
                                            End If
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        End If
        'End If




        Return workingTime
    End Function

    Public Function GetStatusNow() As String
        'Dim workingTime As Integer = 0
        Dim stt As String = ""
        Dim now As String = DateTime.Now.ToString("HH:mm")

        'If now.CompareTo(TimeSche.MorStart) < 0 Then
        '    workingTime = CountTimeSpan(now, TimeSche.MorStart)
        'Else
        If now.CompareTo(TimeSche.MorBreakStart) < 0 Then
            stt = "MorStart"
        Else
            If now.CompareTo(TimeSche.MorBreakEnd) < 0 Then
                stt = "MorBreakStart"
            Else
                If now.CompareTo(TimeSche.LunchStart) < 0 Then
                    stt = "MorBreakEnd"
                Else
                    If now.CompareTo(TimeSche.LunchEnd) < 0 Then
                        stt = "LunchStart"
                    Else
                        If now.CompareTo(TimeSche.NoonStart) < 0 Then
                            stt = "LunchEnd"
                        Else
                            If now.CompareTo(TimeSche.NoonBreakStart) < 0 Then
                                stt = "NoonStart"
                            Else
                                If now.CompareTo(TimeSche.NoonBreakEnd) < 0 Then
                                    stt = "NoonBreakStart"
                                Else
                                    If now.CompareTo(TimeSche.NoonEnd) < 0 Then
                                        stt = "NoonBreakEnd"
                                    Else
                                        'if not OT
                                        If TimeSche.OTStart.Length = 0 Then
                                            stt = "NoonEnd"
                                        Else
                                            'if OT
                                            If now.CompareTo(TimeSche.OTStart) < 0 Then
                                                stt = "NoonEnd"
                                            Else
                                                If now.CompareTo(TimeSche.OTEnd) < 0 Then
                                                    stt = "OTStart"
                                                Else
                                                    stt = "OTEnd"
                                                End If
                                            End If
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        End If
        'End If




        Return stt
    End Function

    Public Function CountPlan() As Integer
        Dim workingTime As Integer = CountWorkingTimeToNow()

        If workingTime <= 0 Then
            Return 0
        End If

        Dim planAtNow As Integer = 0
        For Each item As Item In LstTargetToday
            If workingTime > 0 Then
                workingTime -= item.Duration
                If (Not item.Model.Equals("change")) AndAlso workingTime > 0 Then
                    planAtNow += 1
                End If
            End If
        Next

        Return planAtNow
    End Function

    'call this method when starting app after power-off (not at begining day)
    Public Sub AddTargetToLstTarget()
        Try
            Using sr As New StreamReader("targettoday.txt")
                Dim dateInFile As String = sr.ReadLine()
                Dim today As String = DateTime.Now.ToString("MM/dd/yyyy")
                If today.Equals(dateInFile) Then
                    Dim line As String
                    While sr.Peek() <> -1
                        line = sr.ReadLine()
                        Dim split As String() = line.Split("|")
                        Dim mo As String = split(0)
                        Dim du As String = split(1)
                        Dim ttc As String = split(2)
                        Dim iDu As Integer = Integer.Parse(du)
                        Dim iTtc As Integer = Integer.Parse(ttc)
                        Dim item As Item = New Item(mo, iDu, iTtc)
                        LstTargetToday.Add(item)
                    End While
                End If
            End Using
        Catch e As Exception
            MessageBox.Show("'targettoday.txt' could not be read!")
        End Try
    End Sub

    'at begining day, call this method to save target today in case power-off
    Public Sub SaveTargetToday()
        Dim path As String = "targettoday.txt"
        Try
            Dim file As New StreamWriter(path)
            file.WriteLine(DateTime.Now.ToString("MM/dd/yyyy"))
            For Each item As Item In LstItem
                file.WriteLine(item.Model + "|" + item.Duration.ToString() + "|" + item.TimeToChange.ToString())
            Next
            file.Close()
        Catch e As Exception
            MessageBox.Show("'targettoday.txt' could not be editted!")
        End Try
    End Sub

    'Update working hour
    'Host: 		WORK|07:30|...
    Public Sub SaveWorkMsg(ByVal msg As String)
        Dim path As String = "timer.txt"
        Try
            Dim file As New StreamWriter(path)

            'remove title of msg (5 first letters)
            msg = msg.Substring(5)
            Dim split As String() = msg.Split("|")

            For Each s As String In split
                file.WriteLine(s)
            Next

            file.Close()
        Catch e As Exception
            MessageBox.Show("Cannot save working time!")
        End Try
    End Sub

    'Update Schedule
    'Host:		SCHE|MMddyyyy|Model1|qty|changeTime|duration|Model2|...
    Public Sub SaveScheMsg(ByVal msg As String)
        'remove title of msg (5 first letters)
        msg = msg.Substring(5)

        Dim strDate As String = msg.Substring(0, 8)
        Dim path As String = "schedule_" + strDate + ".txt"
        Try
            Dim file As New StreamWriter(path)

            strDate = strDate.Insert(4, "/")
            strDate = strDate.Insert(2, "/")

            file.WriteLine(strDate)

            'remove date of msg (9 first letters)
            msg = msg.Substring(9)

            Dim split As String() = msg.Split("|")

            Dim record As String = ""

            'record = Model1|qty|changeTime|duration
            For i As Integer = 0 To split.Length - 1
                record = record & split(i) & "|"
                If i Mod 4 = 3 Then
                    record = record.Remove(record.Length - 1)
                    file.WriteLine(record)
                    record = ""
                End If
            Next

            file.Close()
        Catch e As Exception
            MessageBox.Show("Cannot update schedule!")
        End Try
    End Sub

    'Ask Schedule
    'Host		ASKS|MMddyyyy
    'Client		ShopName|MMddyyyy|Model1|qty|changeTime|duration|Model2|...
    Public Function ReplyAskSchedule(ByVal msg As String) As String
        Dim reply As String = ShopName & "|"
        Dim strDate As String = msg.Substring(5)
        Dim path As String = "schedule_" + strDate + ".txt"
        reply = reply & strDate & "|"
        Try
            Using sr As New StreamReader(path)
                Dim line As String
                'the 1st line is MM/dd/yyyy => do nothing
                line = sr.ReadLine()
                While sr.Peek() <> -1
                    line = sr.ReadLine()
                    reply = reply & line & "|"
                End While
                reply = reply.Remove(reply.Length - 1)
            End Using
        Catch e As Exception
            MessageBox.Show("Cannot reply schedule!")
        End Try

        Return reply
    End Function

    Public Sub DoWork()
        LstItem(0).Duration -= 1
        If LstItem(0).Duration = 0 Then
            'if model = change, do nothing
            'if model != change, update number
            If Not LstItem(0).Model.Equals("change") Then
                LstItem.RemoveAt(0)
                Plan += 1
                Diff = Plan - Actual
                lblPlan.Text = Plan.ToString()
                lblDiff.Text = Diff.ToString()
                SaveNumberFile()
            End If
        End If
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        lblTime.Text = DateTime.Now.ToString("HH:mm")
        Dim now As String = ConvertTimeToString(DateTime.Now)

        Select Case Status
            Case ""
                If now.Equals(TimeSche.MorStart) Then
                    Status = "MorStart"
                    SaveStatus("MorStart")
                End If

            Case "MorStart"
                DoWork()
                If now.Equals(TimeSche.MorBreakStart) Then
                    Status = "MorBreakStart"
                    SaveStatus("MorBreakStart")
                End If

            Case "MorBreakStart"
                If now.Equals(TimeSche.MorBreakEnd) Then
                    Status = "MorBreakEnd"
                    SaveStatus("MorBreakEnd")
                End If

            Case "MorBreakEnd"
                DoWork()
                If now.Equals(TimeSche.LunchStart) Then
                    Status = "LunchStart"
                    SaveStatus("LunchStart")
                End If

            Case "LunchStart"
                If now.Equals(TimeSche.LunchEnd) Then
                    Status = "LunchEnd"
                    SaveStatus("LunchEnd")
                End If

            Case "LunchEnd"
                If now.Equals(TimeSche.NoonStart) Then
                    Status = "NoonStart"
                    SaveStatus("NoonStart")
                End If

            Case "NoonStart"
                DoWork()
                If now.Equals(TimeSche.NoonBreakStart) Then
                    Status = "NoonBreakStart"
                    SaveStatus("NoonBreakStart")
                End If

            Case "NoonBreakStart"
                If now.Equals(TimeSche.NoonBreakEnd) Then
                    Status = "NoonBreakEnd"
                    SaveStatus("NoonBreakEnd")
                End If

            Case "NoonBreakEnd"
                DoWork()
                If now.Equals(TimeSche.NoonEnd) Then
                    Status = "NoonEnd"
                    SaveStatus("NoonEnd")
                End If

            Case "NoonEnd"
                If TimeSche.OTStart.Length > 0 Then
                    If now.Equals(TimeSche.OTStart) Then
                        Status = "OTStart"
                        SaveStatus("OTStart")
                    End If
                End If

            Case "OTStart"
                If TimeSche.OTEnd.Length > 0 Then
                    DoWork()
                    If now.Equals(TimeSche.OTEnd) Then
                        Status = "OTEnd"
                        SaveStatus("OTEnd")
                    End If
                End If



            Case Else

        End Select

        If CountWorkingTimeToNow() > 0 Then
            SavePendingFile()
        End If


        lblStatus.Text = Status

    End Sub

    Private Sub btnDone_Click(sender As Object, e As EventArgs) Handles btnDone.Click
        Actual += 1
        Diff = Plan - Actual
        lblActual.Text = Actual.ToString()
        lblDiff.Text = Diff.ToString()
        SaveNumberFile()

        'send msg to host
        CountTimesSendingMsg = 0
        TimerSendMsg.Enabled = True
    End Sub

    Public Sub SendMsgToHost()
        Dim msg As String
        'ShopName|Plan|Actual
        msg = ShopName & "|" & Plan.ToString() & "|" & Actual.ToString()
        Tcp.SendData(msg, RemoteAddr, RemotePort)
    End Sub

    Private Sub TimerSendMsg_Tick(sender As Object, e As EventArgs) Handles TimerSendMsg.Tick
        If CountTimesSendingMsg < 5 Then
            SendMsgToHost()
            CountTimesSendingMsg += 1
        End If
    End Sub

    Public Sub ConnetTCP()

        Dim strHostName As String = Dns.GetHostName()
        Dim ipEntry As IPHostEntry = Dns.GetHostEntry(strHostName)
        HostAddr = ipEntry.AddressList(0).ToString()
        HostPort = 5000
        Tcp.connect(HostAddr, HostPort)
    End Sub

    'handle receiving msg from host
    Public Sub myChat_Datareceived(txt As String) Handles Tcp.Datareceived
        'lbout.Items.Add(Now & " >>In >> " & txt)
        'MessageBox.Show(txt)

        If txt.Length > 4 Then
            Dim reply As String = ""
            Dim title As String = txt.Substring(0, 4)

            Select Case title
                Case "WORK"
                    SaveWorkMsg(txt)
                    reply = ShopName & "|OK"
                Case "SCHE"
                    SaveScheMsg(txt)
                    reply = ShopName & "|OK"
                Case "ASKS"
                    reply = ReplyAskSchedule(txt)
                Case "ONLN"
                    reply = ShopName & "|OK"
                Case Else

            End Select

            Tcp.SendData(reply, RemoteAddr, RemotePort)
        Else
            'when host received msg from this sshop
            If txt.Equals("OK") Then
                TimerSendMsg.Enabled = False
                TimerSendMsg.Stop()
            End If
        End If

    End Sub


End Class